package service

import (
	"singo/model"
	"singo/serializer"
	"time"
)

// ProjectUpdateService 更新项目的服务
type ProjectUpdateService struct {
	ID              string `form:"id" json:"id" binding:"required"`
	Name            string `form:"name" json:"name" binding:"max=30"`
	Head            string `form:"head" json:"head"`
	Intro           string `form:"intro" json:"intro"`
	Status          int    `form:"status" json:"status"`
	Score           uint   `form:"score" json:"score"`
	OrganizationUID string `form:"organization_id" json:"organization_id"`
	DeadlineAt      string `form:"deadline_at" json:"deadline_at"`
}

// ProjectUpdate 更新项目
func (service *ProjectUpdateService) ProjectUpdate() *serializer.Response {
	var project model.Project
	err := model.DB.First(&project, "uid = ?", service.ID).Error
	if err != nil {
		return &serializer.Response{
			Status: 404,
			Msg:    "不存在",
			Error:  err.Error(),
		}
	}

	if service.DeadlineAt != "" {
		deadlineAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.DeadlineAt, time.Local)
		project.DeadlineAt = &deadlineAt
	} else {
		project.DeadlineAt = nil
	}

	project.Name = service.Name
	project.Head = service.Head
	project.Intro = service.Intro
	project.Status = service.Status
	project.OrganizationUID = service.OrganizationUID
	err = model.DB.Save(&project).Where("uid = ?", service.ID).Error
	if err != nil {
		return &serializer.Response{
			Status: 50002,
			Msg:    "项目保存失败",
			Error:  err.Error(),
		}
	}

	return &serializer.Response{
		Data:   true,
		Msg:    "成功",
		Status: 0,
	}
}
